package it.cast.wechat.cotroller;

import it.cast.wechat.dto.OrderItemVo;
import it.cast.wechat.pojo.OrderItem;
import it.cast.wechat.pojo.Product;
import it.cast.wechat.service.OrderItemService;
import it.cast.wechat.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.*;

@Controller
public class OrderItemController {

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ProductService productService;

    @RequestMapping("cartItem/queryOrderItemByOrderId")
    @ResponseBody
    public List<OrderItemVo> queryOrderItemByOrderId(String orderId){
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<OrderItem> orderItems = orderItemService.queryOrderItemByOrderId(orderId);
        List<OrderItemVo> collect = orderItems
                .stream()
                .map(orderItem -> {
                    OrderItemVo orderItemVo = orderItem.builderOrderItemVo();
                    String productId = orderItem.getProductId();
                    Optional<Product> opt = productService.queryProduct(productId);
                    opt.ifPresent(orderItemVo::setProduct);
                    return orderItemVo;
                })
                .collect(toList());

        return collect;
    }
}
